#!/bin/bash

prefix=/usr/local
kerneldir=/lib/modules/$(uname -r)/build
want_module=1
qemu_cc=
qemu_cflags=
qemu_ldflags=
qemu_opts=
cross_prefix=
arch=`uname -m`
target_exec=

usage() {
    cat <<-EOF
	Usage: $0 [options]

	Options include:
	    --arch=ARCH            architecture to compile for ($arch)
	    --cross-prefix=PREFIX  prefix for cross compile
	    --prefix=PREFIX        where to install things ($prefix)
	    --with-patched-kernel  don't use external module
	    --kerneldir=DIR        kernel build directory ($kerneldir)
	    --qemu-cc=CC           specify compiler for qemu (must be gcc-3.x)
	    --qemu-cflags=CFLAGS   CFLAGS to add to qemu configuration
	    --qemu-ldflags=LDFLAGS LDFLAGS to add to qemu configuration

	Any additional option is given to qemu's configure verbatim; including:

	    --disable-gcc-check    don't insist on gcc-3.x
	                           CAUTION: this will break running without kvm
EOF
}

while [[ "$1" = -* ]]; do
    opt="$1"; shift
    arg=
    if [[ "$opt" = *=* ]]; then
	arg="${opt#*=}"
	opt="${opt%%=*}"
    fi
    case "$opt" in
	--prefix)
	    prefix="$arg"
	    ;;
	--kerneldir)
	    kerneldir="$arg"
	    ;;
	--with-patched-kernel)
	    want_module=
	    ;;
	--qemu-cc)
	    qemu_cc="$arg"
	    ;;
	--qemu-cflags)
	    qemu_cflags="$arg"
	    ;;
	--qemu-ldflags)
	    qemu_ldflags="$arg"
	    ;;
	--arch)
	    arch="$arg"
	    ;;
	--cross-prefix)
	    cross_prefix="$arg"
            ;;
	--help)
	    usage
	    ;;
	*)
	    qemu_opts="$qemu_opts $opt"
	    ;;
    esac
done


#set kenel directory
libkvm_kerneldir="$kerneldir"
if (( want_module )); then
    libkvm_kerneldir=$(readlink -f kernel)
fi

#if arch is an x86 arch set to i386
if [[ $arch = i?86 ]]; then
  arch="i386"
fi

#set parameters compiling
if [ "$arch" = "i386" -o "$arch" = "x86_64" ]; then
    target_exec="x86_64-softmmu"
    qemu_cflags="$qemu_cflags -DCONFIG_X86"
fi

if [ "$arch" = "ia64" ]; then
    target_exec="ia64-softmmu"
fi

if [ "$arch" = "powerpc" ]; then
    target_exec="ppcemb-softmmu"
    qemu_cflags="$qemu_cflags -I $PWD/libfdt"
    qemu_ldflags="$qemu_ldflags -L $PWD/libfdt"
fi

cat <<EOF > config.mak
ARCH=$arch
PREFIX=$prefix
KERNELDIR=$kerneldir
WANT_MODULE=$want_module
CROSS_COMPILE=$cross_prefix
EOF
